package com.och.mrcp.config;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "netty")
@Data
public class NettyConfig {
    
    private int bossThreads = 2;
    private int workerThreads = 16;
    private int port = 5060;
    private int connectTimeoutMillis = 10000;
    private int writeTimeoutMillis = 10000;
    private int readTimeoutMillis = 30000;
    
    @Bean(destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup(bossThreads);
    }
    
    @Bean(destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup(workerThreads);
    }
    
    @Bean
    public ServerBootstrap tcpServerBootstrap() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_RCVBUF, 131072)    // 128KB接收缓冲区
                .childOption(ChannelOption.SO_SNDBUF, 131072)    // 128KB发送缓冲区
                .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, 
                    new WriteBufferWaterMark(32 * 1024, 64 * 1024)); // 写缓冲区水位
        return bootstrap;
    }
    
    @Bean
    public Bootstrap udpBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup())
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, 131072)         // 128KB接收缓冲区
                .option(ChannelOption.SO_SNDBUF, 131072)         // 128KB发送缓冲区
                .option(ChannelOption.SO_REUSEADDR, true);
        return bootstrap;
    }
}
